// 处理dataset
import { PrismaClient } from "@prisma/client";
import Router from "koa-router";
import fs from "fs";
import path from "path";

const prisma = new PrismaClient();

const datasetRouter = new Router();

datasetRouter.prefix("/dataset");

datasetRouter.get("/", async (ctx) => {
  const dataset = await prisma.dataset.findMany();
  ctx.body = dataset;
});

datasetRouter.get("/name-list", async (ctx) => {
  const dataset = await prisma.dataset.findMany({
    select: { id: true, name: true },
    orderBy: { id: "asc" },
  });
  ctx.body = dataset.map((item) => item.name);
});

datasetRouter.delete("/:name", async (ctx) => {
  const { name } = ctx.params;

  await prisma.dataset.delete({
    where: { name },
  });

  const deletePath = path.join(process.cwd(), "app", "dataset", name);

  deleteFolderRecursive(deletePath);

  ctx.body = "ok";
});

export function deleteFolderRecursive(deletePath: string) {
  if (!fs.existsSync(deletePath)) return;
  if (!fs.statSync(deletePath).isDirectory()) return fs.unlinkSync(deletePath);
  for (let node of fs.readdirSync(deletePath)) {
    const curPath = path.join(deletePath, node);
    deleteFolderRecursive(curPath);
  }
  fs.rmdirSync(deletePath);
}

export default datasetRouter;
